<template>
  <MainLayout>
    <view class="page">
      <!-- 页面标题 -->
      <view class="page-header">
        <image src="/static/icons/pageReturn.svg" mode="aspectFit" class="back-icon" @click="goBack"></image>
        <text class="title">编辑个人资料</text>
      </view>

      <!-- 编辑表单 -->
      <view class="form-container">
        <view class="avatar-section">
          <image :src="userInfo.avatarUrl || '/static/icons/default-avatar.png'" mode="aspectFill" class="avatar-img"></image>
          <button class="upload-btn slim-btn" @click="uploadAvatar">上传头像</button>
        </view>

        <view class="input-item">
          <text class="label">昵称</text>
          <input 
            type="text" 
            class="input-field" 
            v-model="userInfo.nickname"
            placeholder="请输入昵称"
          />
        </view>

        <view class="input-item">
          <text class="label">个性签名</text>
          <input 
            type="text" 
            class="input-field" 
            v-model="userInfo.signature"
            placeholder="请输入个性签名"
          />
        </view>
      </view>
      
      <!-- 保存按钮 -->
      <view class="save-section">
        <button class="save-btn slim-btn" @click="saveProfile">保存</button>
      </view>
    </view>
  </MainLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import MainLayout from '../../layout/MainLayout.vue'
import userApi from '../../http/models/user.ts'

// 用户信息
const userInfo = ref({
  userId: '',
  avatarUrl: '',
  nickname: '',
  signature: ''
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const storedUserInfo = uni.getStorageSync('userInfo')
    if (storedUserInfo) {
      userInfo.value = {...userInfo.value, ...storedUserInfo}
    } else {
      // 如果本地没有用户信息，则通过API获取
      const userId = uni.getStorageSync('userId')
      if (userId) {
        const res = await userApi.getUserInfo(userId)
        if (res.code === 200) {
          userInfo.value = {...userInfo.value, ...res.data}
          // 同步更新本地存储
          uni.setStorageSync('userInfo', res.data)
        }
      }
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}

// 上传头像
const uploadAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      // 这里应该调用上传图片的API
      // 示例代码：
      // uploadImage(tempFilePath).then(url => {
      //   userInfo.value.avatarUrl = url
      // })
      
      // 暂时使用本地路径作为演示
      userInfo.value.avatarUrl = tempFilePath
      uni.showToast({
        title: '头像上传成功',
        icon: 'success'
      })
    },
    fail: (err) => {
      console.error('选择图片失败', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 保存个人资料
const saveProfile = async () => {
  if (!userInfo.value.nickname) {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none'
    })
    return
  }
  
  try {
    // 调用API更新用户信息
    const updateParams = {
      userId: userInfo.value.userId,
      nickname: userInfo.value.nickname,
      signature: userInfo.value.signature
    }
    
    // 只有当头像URL不是本地临时路径时才更新头像
    if (userInfo.value.avatarUrl && !userInfo.value.avatarUrl.startsWith('http')) {
      // 这里应该调用上传头像的API，并将返回的URL加入参数
      // 示例：updateParams.avatarUrl = uploadedUrl
    }
    
    const updateRes = await userApi.updateUser(updateParams)
    
    if (updateRes.code === 200) {
      // 更新本地存储和页面显示
      uni.setStorageSync('userInfo', userInfo.value)
      uni.showToast({
        title: '资料更新成功',
        icon: 'success'
      })
      
      // 延迟返回上一页，给用户看到成功提示
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: updateRes.msg || '更新失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('更新资料失败', error)
    uni.showToast({
      title: '更新失败，请稍后重试',
      icon: 'none'
    })
  }
}

const goBack = () => {
  uni.switchTab({
    url: '/pages/mine/mine'
  })
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.page {
  width: 100%;
  min-height: calc(100vh - 50px);
  background: white;
  padding: 15px 0;
  box-sizing: border-box;
}

/* 页面标题 */
.page-header {
  margin-top: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-align: center;
  flex: 1;
}

.save-btn {
  background-color: #8CE090;
  color: white;
  border: none;
  margin: 8px 15px;
  border-radius: 5px;
  font-size: 14px;
}

/* 表单容器 */
.form-container {
  margin: 0 15px;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar-img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 15px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.upload-btn {
  background-color: #E6F7E9;
  color: #4CAF50;
  border: none;
  margin: 8px 15px;
  border-radius: 5px;
  font-size: 14px;
}

/* 输入项 */
.input-item {
  margin-bottom: 20px;
}

.label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.input-field {
  border: 1px solid #E5E5E5;
  border-radius: 8px;
  height: 48px;
  padding: 0 15px;
  color: #333;
  font-size: 14px;
  width: 100%;
  background: white;
}
</style>